#-*- coding:utf-8 -*-
import os
import sys
import shutil
import platform
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from Widgets.rename import Rename
from Widgets.delete_warn import DeleteWarn
from Windows.CreateDepartment import CreateDepartment


class DepartmentWidget(QWidget):
    name_Signal = Signal(str)  # 当前选择的项目，发射信号
    departmentPath_epiList_Signal=Signal(tuple)#选中部门时，将当前部门真实路径与部门里集数列表发出去
    departmentPath_epiList_epiName_Signal=Signal(tuple)#查询更新部门后，自动刷新集数并指定集数

    def __init__(self):
        super(DepartmentWidget,self).__init__()

        # 全局变量

        self.real_project_path=''
        self.real_department_path=''
        self.mainLayout = QVBoxLayout()


        self.scrollArea = QScrollArea()  # 滚动窗口，需要添加self.scroll_widget进来

        self.scroll_widget = QWidget()  # 滚动窗口添加的内组件
        self.scroll_widget.setMinimumHeight(300)
        self.scroll_layout = QVBoxLayout()  # 滚动组件self.scroll_widget的布局，这里动态添加radiobutton
        # self.scroll_layout.setSpacing(20)
        self.scroll_layout.setAlignment(Qt.AlignTop)

        self.radio_department_list = []  # 总的部门列表

        self.mainLayout.addWidget(self.scrollArea)

        self.setLayout(self.mainLayout)
        # 添加右击菜单
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.__rightMenu)

        self.current_project = ''
        self.current_department='' #当前部门
        # self.setLayout(self.mainLayout)

    def setRadioBtnList(self,nameList):
        self.radio_department_list = nameList
        try:
            for i in range(self.scroll_layout.count()):  # 先把以前的列表删除干净
                self.scroll_layout.itemAt(i).widget().deleteLater()
        except:
            pass

        for i in nameList:
            radio_btn = QRadioButton(i)
            radio_btn.setMinimumWidth(100)
            radio_btn.setStyleSheet("QRadioButton:hover{color :#33FF00}")
            radio_btn.clicked.connect(self.__showNameSlot)
            self.scroll_layout.addWidget(radio_btn)

            # QApplication.processEvents()

        self.scroll_widget.setLayout(self.scroll_layout)  # 添加布局
        self.scrollArea.setWidget(self.scroll_widget)

        # self.setLayout(self.mainLayout)


    def setCurrentRadioBtn(self,department_path,department_name):
        '''
        设置当前选择,Radio btn的特性只要设置为True那么其他就自动变成False
        :param department_path:部门路径
        :param department_name:部门名称
        :return: 设置完后，发个不一样的信号过去给主界面跟不仅包括部门路径与部门名称，还得有集数名称信息(其实没必要发射信号过去)
        '''
        for i in range(self.mainLayout.count()):
            w=self.scroll_layout.itemAt(i).widget()
            if w.text()==department_name:
                w.setChecked(True)

        # epi_list=os.listdir(department_path)
        # temp_tuple=(department_name,department_path,epi_list)
        # self.departmentPath_epiList_epiName_Signal.emit(temp_tuple)

    def setCurrentProjectName(self,projectName):
        '''
        该函数主要是用于在点击项目窗口后setCurrentProjectName设置主窗口全局变量的同时，让部门窗口也获取该值
        :param projectName:
        :return:
        '''
        self.current_project=projectName

    def setRealProjectPath(self,real_project_path):
        '''
        该函数为设置当前真实项目路径，主界面每次点击项目名称时发射过来
        :param real_project_path:
        :return:
        '''
        self.real_project_path=real_project_path

    def deleteCurrentRadioBtn(self):
        '''
        因为是RadioButton所以除非一开始为空，必然选中的就是当前的，所以该方法可以直接调用
        :return:
        '''
        if self.current_department is not '':
            self.radio_department_list.remove(self.current_department)
            for i in range(self.scroll_layout.count()):
                self.scroll_layout.itemAt(i).widget().deleteLater()
            self.__removeProject(self.current_department)
            self.setRadioBtnList(self.radio_department_list)
        else:
            QMessageBox.information(self, '提示', '请先选择项目')

    def __showNameSlot(self):
        btn = self.sender()
        name = btn.text()
        self.current_department = name
        self.real_department_path=os.path.join(self.real_project_path,self.current_department)
        epi_list=os.listdir(self.real_department_path)
        temp_tuple=(self.current_department,self.real_department_path,epi_list)
        self.departmentPath_epiList_Signal.emit(temp_tuple)

        # print(self.current_department)
        # print(temp_tuple)

    def renameBtn(self):
        '''
        打开重命名窗口rename.py,对本地项目信息以及真实项目目录进行重命名
        :return:
        '''
        if self.current_department is '':
            QMessageBox.information(self, '提示', '请先选择部门')
        else:
            self.rename = Rename(self.current_department)
            self.rename.newName_Signal.connect(self.__rename)
            self.rename.show()


    def __rename(self, new_name):
        '''
        计算函数，对真实部门名称进行更改
        :param origin_name: 就是当前选中的部门
        :param new_name:
        :return: 注意改名完后，要刷新self.current_department才行
        '''
        origin_department_path = os.path.join(self.real_project_path,self.current_department)
        new_department_path=os.path.join(self.real_project_path,new_name)
        temp_list=os.listdir(self.real_project_path)
        if origin_department_path:  # 当存在时
            if new_name not in temp_list:
                try:
                    os.rename(origin_department_path,new_department_path)
                    temp_list.remove(self.current_department)
                    temp_list.append(new_name)
                    self.current_department=new_name

                    self.setRadioBtnList(temp_list)
                except:
                    QMessageBox.information(self,"注意",'当前目录下有文件打开')



    def __rightMenu(self):
        self.menu = QMenu()

        self.addAction = QAction(u'添加部门', self)
        self.addAction.triggered.connect(self.addBtn)
        self.menu.addAction(self.addAction)

        self.renameAction = QAction(u'重命名', self)
        self.renameAction.triggered.connect(self.renameBtn)
        self.menu.addAction(self.renameAction)

        self.deleteAction = QAction(u'删除', self)
        self.deleteAction.triggered.connect(self.__deleteBtn)
        self.menu.addAction(self.deleteAction)

        self.openAction=QAction(u'打开目录',self)
        self.openAction.triggered.connect(self.__open)
        self.menu.addAction(self.openAction)


        self.menu.exec_(QCursor.pos())


    def addBtn(self):
        '''
        添加集数，这里打开创建集数窗口

        :return:
        '''
        if self.current_project !='':
            self.createDepartmentWindow=CreateDepartment(self.real_project_path)
            self.createDepartmentWindow.department_Signal.connect(self.setRadioBtnList)#创建部门返回的就是已经创建完后所有的部门列表
            self.createDepartmentWindow.show()
        else:
            QMessageBox.information(self,'提示','请先选择一个项目')




    def __deleteBtn(self):
        '''
        删除部门按钮，删除部门要来真的，直接删除真实路径下目录
        :return:
        '''
        self.dw=DeleteWarn(1)
        self.dw.out_Signal.connect(self.__real_delete)
        self.dw.show()

    def __real_delete(self,back):
        '''
        最终删除函数
        :param back:
        :return:
        '''
        if back==1:
            btn = self.focusWidget()
            current_department = btn.text()
            if current_department in self.radio_department_list:
                self.radio_department_list.remove(current_department)

                self.__removeDepartment(current_department)
                self.setRadioBtnList(self.radio_department_list)
        else:
            pass

    def __removeDepartment(self,department):
        '''
        中间计算函数，不能用于外面调用
        :param name:
        :return:
        '''

        real_department_path=os.path.join(self.real_project_path,department)
        try:
            shutil.rmtree(real_department_path,True)

        except:
            QMessageBox.information(self,"提示","该目录下有文件正被使用")

    def __open(self):
        '''
        打开当前右击选择的部门目录
        :return:
        '''

        btn = self.focusWidget()
        if not btn.text():
            QMessageBox.information(self,'提示','鼠标请放在正确的集/场名上')
        else:
            choose_department = btn.text()
            choose_department_path=os.path.join(self.real_project_path,choose_department)
            try:
                sysstr = platform.system()
                if sysstr == "Windows":
                    os.startfile(choose_department_path.replace('/', '\\'))
                else:
                    os.startfile(choose_department_path)
            except:
                QMessageBox.information(self,'提示','该部门不存在')



if __name__ == '__main__':
    app = QApplication()
    R = DepartmentWidget()
    nameList = ['a', 'b', 'c', 'd', 'e']
    R.setRadioBtnList(nameList)
    R.show()
    sys.exit(app.exec_())


